var tabH = [{
    name: "商品",
    id:'0'
  },
  {
    name: "服务",
    id: '1'
  }, {
    name: "详情",
    id: '2'
  }
];
const HtmlParser = require('../../html-view/index');
var util = require('../../utils/util.js');
Page({
  data: {
    idx:'',
    hasDetails: false, //是否有详情
    hasEvaluate: false, //是否有评价
    evaluateNum: 0, //评价数量
    tabH: tabH,
    status: 0,
    select:0,
    imgUrls: [], //焦点图
    indicatorDots: true,
    autoplay: true,
    interval: 3000,
    duration: 500,
    indicatorActiveColor: '#fa7d35',
    tabCollect: false, //商品收藏初始化状态
    clickId: 0,
    num: 0,
    hiddenName: false, //点击加入购物车
    cartNum: 0, //购物车商品数量
    goods_name: '', //商品名称
    store_name: '', //店铺名称
    store_logo: '', //店铺logo
    store_desccredit: '', //店铺描述
    store_servicecredit: '', //店铺服务
    store_deliverycredit: '', //物流服务
    goods_price: '', //商品价格
    goods_unit: '', //商品规格
    goods_marketprice: '', //商品原价
    goods_eval_list: '', //商品评价列表
    geval_addtime: '', //评价时间
    geval_scores1: 0,
    tabs: [], //商品所有规格
    goods_id: "", //商品id
    item: "", //外部传进来的数据
    store_id: '', //店铺id
    JSONGoodsId: '', //收藏商品转换为JOSN格式
    goods_info: "",
  },
  onShow: function(options) {
    wx.showShareMenu({
      withShareTicket: true
    })
    console.log("show_option = ", options);
  },
  onLoad: function(options) {
    //页面加载默认没有收藏
    var that = this;
    wx.showShareMenu({
      withShareTicket: true
    })
    var item = JSON.parse(options.item);
    console.log(item);
    if (wx.getStorageSync('token') == '') {
      that.setData({
        num: item.num,
      })
    }
    that.initRed();
    that.getDetail(item.goods_id);
  },
  //切换
  navTabClick(e) {
    console.log('切换', e.currentTarget.dataset.index)
    var index = e.currentTarget.dataset.index;
    this.setData({
      status: index,
      select: -1
    })
  },
  // 触顶切换
  bindscroll(e) {
    var that = this;
    var scrollTop = e.detail.scrollTop;
    console.log('距顶部距离', e.detail.scrollTop);
    if (e.detail.scrollTop <= '100'){
      that.setData({
        select: 0,
        status:-1
      })
    } else if ('101' <= e.detail.scrollTop && e.detail.scrollTop<='929'){
      that.setData({
        select: 1,
        status: -1
      })
    } 
    else{
      that.setData({
        select: 2,
        status: -1
      })
   }
  },
  getDetail: function(id) {
    var that = this;
    util.postUrl('/goods/detail', {
      goods_id: id,
    }, function(res) {
      if (res.data.code == 200) {
        var goodsItem = res.data.datas;
        var item = goodsItem.goods_info;
        if (wx.getStorageSync('token') == '') {
          item.num = that.data.num;
        } else {
          item.num = parseInt(goodsItem.goods_info.carts_num);
        }
        that.setData({
          goods_id: item.goods_id,
          num: item.num,
          item: item,
        })

        for (var item1 of goodsItem.goods_eval_list) {
          item1.geval_scores = parseInt(item1.geval_scores);
        }
        const html = new HtmlParser(goodsItem.goods_info.mobile_body).nodes;
        if (goodsItem.goods_info.mobile_body == '') {
          that.setData({
            hasDetails: false
          })
        } else {
          that.setData({
            hasDetails: true
          })
        }
        that.setData({
          html: html,
          imgUrls: goodsItem.goods_image,
          goods_name: goodsItem.goods_info.goods_name,
          store_name: goodsItem.store_info.store_name,
          store_logo: goodsItem.store_info.store_avatar,
          store_desccredit: goodsItem.store_info.store_credit.store_desccredit.credit,
          store_servicecredit: goodsItem.store_info.store_credit.store_servicecredit.credit,
          store_deliverycredit: goodsItem.store_info.store_credit.store_deliverycredit.credit,
          goods_price: goodsItem.goods_info.goods_price,
          goods_info: goodsItem.goods_info,
          goods_unit: goodsItem.goods_info.goods_unit,
          goods_marketprice: goodsItem.goods_info.goods_marketprice,
          goods_eval_list: goodsItem.goods_eval_list,
          geval_addtime: goodsItem.goods_eval_list.geval_addtime,
          tabs: goodsItem.goods_list,
          store_id: goodsItem.store_info.store_id,
          goods_id: goodsItem.goods_info.goods_id,
          tabCollect: goodsItem.goods_info.is_favorate
        });
      };
      var postCollected = that.data.goods_id;
      wx.setStorageSync('goods_id', that.data.goods_id)
    })
  },

  //商品规格选择
  tabClick: function(res) {
    var that = this;
    var item = res.currentTarget.dataset.item;
    var index = res.currentTarget.dataset.index;
    console.log(item);
    that.setData({
      clickId: index,
      clickItem: that.data.tabs[index],
    })
    that.getDetail(item.goods_id);
  },

  //点击切换收藏
  onChangeCollect(even) {
    var that = this;
    that.setData({
      tabCollect: (!that.data.tabCollect),
      JSONGoodsId: JSON.stringify(Array(that.data.goods_id))
    })
    console.log('ddddd', that.data.tabCollect)
    if (that.data.tabCollect == true) {
      util.postUrl('member_favorites/goods_add', {
        goods_id: that.data.goods_id
      }, function(res) {
        if (res.data.code == 200) {
          wx.showToast({
            title: '商品收藏成功',
            icon: 'none'
          })
        }
      })
    }
    if (that.data.tabCollect == false) {
      util.postUrl('member_favorites/goods_del', {
        goods_id_list: that.data.JSONGoodsId
      }, function(res) {
        if (res.data.code == 200) {
          wx.showToast({
            title: '商品已取消收藏',
            icon: 'none'
          })
        }
      })
    }
  },

  //点击减号
  bindMinus: function() {
    var that = this;
    var item = that.data.item;
    var check_list = wx.getStorageSync('check_list');
    if (check_list == '') {
      check_list = [];
    }
    if (item.num - 1 < 0) {
      return;
    }
    if (wx.getStorageSync('token') == '') {
      var temp_goods = wx.getStorageSync('temp_goods');
      if (temp_goods == '') {
        temp_goods = [];
      }
      for (var i = 0; i < temp_goods.length; i++) {
        if (temp_goods[i].goods_id == item.goods_id) {
          if (item.num - 1 == 0) {
            temp_goods.splice(i, 1);
            if (check_list.indexOf(item.goods_id) != -1) {
              check_list.splice(check_list.indexOf(item.goods_id), 1);
            }
          } else {
            temp_goods[i].quantity = item.num - 1;
            temp_goods[i].goods_num = item.num - 1;
          }
        }
      }
      item.num = item.num - 1;
      that.setData({
        num: item.num
      });
      wx.setStorageSync('temp_goods', temp_goods);
      wx.setStorageSync('check_list', check_list);
      that.initRed();
    } else {
      if (item.num - 1 == 0) {
        util.postUrl("cart/cart_remove", {
          cart_id: item.goods_id,
          del_type: 2,
        }, function(res) {
          if (res) {
            if (check_list.indexOf(item.goods_id) != -1) {
              check_list.splice(check_list.indexOf(item.goods_id), 1);
            }
            wx.setStorageSync("check_list", check_list);
            item.num = item.num - 1;
            that.setData({
              num: item.num
            });
            that.initRed();
          }
        })
      } else {
        util.postUrl('cart/cart_add', {
          goods_id: item.goods_id,
          quantity: item.num - 1,
        }, function(res) {
          if (res) {
            item.num = item.num - 1;
            that.setData({
              num: item.num
            });
            that.initRed();
          } else {}
        })
      }
    }
  },
  /* 点击加号 */
  bindPlus: function() {

    var that = this;
    var item = that.data.item;
    console.log(item);
    var check_list = wx.getStorageSync('check_list');
    if (check_list == '') {
      check_list = [];
    }

    if (wx.getStorageSync('token') == '') {
      var temp_goods = wx.getStorageSync('temp_goods');
      if (temp_goods == '') {
        temp_goods = [];
      }
      var flag = true;
      for (var i = 0; i < temp_goods.length; i++) {
        if (temp_goods[i].goods_id == item.goods_id) {
          temp_goods[i].quantity = item.num + 1;
          temp_goods[i].goods_num = item.num + 1;
          flag = false;
        }
      }
      if (flag) {
        check_list.push(item.goods_id);
        temp_goods.push({
          goods_id: item.goods_id,
          quantity: item.num + 1,
          goods: {
            goods_id: item.goods_id,
            goods_image_url: that.data.imgUrls[0].goods_img,
            goods_name: item.goods_name,
            goods_price: item.goods_price,
            goods_unit: item.goods_unit,
          },
          goods_num: item.num + 1,
          goods_price: item.goods_price,
        });
      }
      item.num = item.num + 1;
      wx.setStorageSync('temp_goods', temp_goods);
      wx.setStorageSync('check_list', check_list);
      that.setData({
        num: item.num,
      });
      console.log('check_list', wx.getStorageSync('check_list'));
      that.initRed();
    } else {
      util.postUrl('cart/cart_add', {
        goods_id: item.goods_id,
        quantity: item.num + 1,
      }, function(res) {
        if (res) {
          if (res.data.code == 400) {
            wx.showToast({
              title: res.data.datas.error,
              icon: 'none',
              duration: 2000
            })
            return;
          }
          if (check_list.indexOf(item.goods_id) == -1) {
            check_list.push(item.goods_id);
          }
          wx.setStorageSync('check_list', check_list);
          console.log(check_list);
          item.num = item.num + 1;
          that.setData({
            num: item.num,
          });
          that.initRed();
        } else {}
      })
    }


  },
  /* 输入框事件 */
  bindManual: function(e) {
    var that = this;
    var item = that.data.item;
    var temp_num = parseInt(item.num);
    // 将数值与状态写回
    console.log(e.detail.value)
    if (e.detail.value == '' || e.detail.value == 0) {
      e.detail.value = 1;
    }
    item.num = parseInt(e.detail.value);
    that.setData({
      num: item.num,
    })
    if (wx.getStorageSync('token') == '') {
      var temp_goods = wx.getStorageSync('temp_goods');
      if (temp_goods == '') {
        temp_goods = [];
      }
      var flag = true;
      for (var i = 0; i < temp_goods.length; i++) {
        if (temp_goods[i].goods_id == item.goods_id) {
          temp_goods[i].quantity = item.num;
          temp_goods[i].goods_num = item.num;
          flag = false;
        }
      }
      if (flag) {
        temp_goods.push({
          goods_id: item.goods_id,
          quantity: item.num,
          goods: {
            goods_id: item.goods_id,
            goods_image_url: temp[index].goods_img,
            goods_name: item.goods_name,
            goods_price: item.goods_price,
            goods_unit: temp[index].goods_unit,
          },
          goods_num: item.num,
          goods_price: item.goods_price,
        });
      }
      that.setData({
        num: item.num
      });
      wx.setStorageSync('temp_goods', temp_goods);
      console.log('temp_goods', wx.getStorageSync('temp_goods'));
      that.initRed();
    } else {
      util.postUrl('cart/cart_add', {
        goods_id: item.goods_id,
        quantity: parseInt(e.detail.value),
      }, function(res) {
        if (res.data.code == 200) {
          that.initRed();

        } else {
          wx.showToast({
            title: res.data.datas.error,
            icon: 'none'
          })
          item.num = temp_num;
          that.setData({
            num: item.num
          });
          that.initRed();
        }
      })
    }
  },


  goShoppingCar: function() {
    wx.switchTab({
      url: '../shoppingCar/shoppingCar',
    })
  },
  // 转发页面：
  onShareAppMessage: function(res) {
    var that = this;
    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log(res.target)
    }
    var userInfo = wx.getStorageSync("userInfo");
    var nickname = "";
    if (userInfo) {
      nickname = userInfo.userInfo.nickName;
    }
    return {
      title: nickname + '超值推荐' + that.data.goods_name,
      path: '/pages/goods-details/goods-details?item=' + JSON.stringify(that.data.item),
      imageUrl: that.data.imgUrls[0],

    }
  },
  //更新购物车气泡数
  initRed: function() {
    var that = this;
    if (wx.getStorageSync('token') == '') {
      var temp_goods = wx.getStorageSync('temp_goods');
      var sum = 0;
      if (temp_goods != '') {
        for (var i = 0; i < temp_goods.length; i++) {
          sum = sum + temp_goods[i].quantity;
        }
      }
      wx.setTabBarBadge({
        index: 2,
        text: sum + "",
      })
      that.setData({
        cartNum: sum,
      })
      if (sum == 0) {
        wx.hideTabBarRedDot({
          index: 2,
        })
      }
    } else {
      util.postUrl('cart/cart_count', {}, function(res) {
        if (res) {
          wx.setTabBarBadge({
            index: 2,
            text: (res.data.datas.count.goods_total_num + ""),
          })
          that.setData({
            cartNum: res.data.datas.count.goods_total_num,
          })
          if (res.data.datas.count.goods_total_num == 0) {
            wx.hideTabBarRedDot({
              index: 2,
            })
            that.setData({
              cartNum: 0,
            })
          }
        }
      })
    }

  },
  //跳转至全部评价页面
  // allEvaluate: function() {
  //   wx.navigateTo({
  //     url: '../evaluate/evaluate',
  //   })
  // },
  // 收藏店铺
  collectStore: function() {
    util.postUrl('member_favorites/store_add', {
      store_id: this.data.store_id
    }, function(res) {
      if (res.data.code == 200) {
        wx.showToast({
          title: '店铺收藏成功',
          icon: 'none'
        })
      } else {
        wx.showToast({
          title: res.data.datas.error,
          icon: 'none'
        })
      }
    })
  },
  goShopDetail() {
    var that = this;
    wx.navigateTo({
      url: '../shop_detail/shop_detail?store_id=' + that.data.store_id
    })
  },
  previewImage: function(e) {
    var that = this;
    var item = e.currentTarget.dataset.item
    wx.previewImage({
      current: item, // 当前显示图片的http链接
      urls: that.data.imgUrls // 需要预览的图片http链接列表
    })
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function(res) {
    var that = this;
    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log(res.target)
    }
    var userInfo = wx.getStorageSync("userInfo");
    var nickname = "";
    if (userInfo) {
      nickname = userInfo.userInfo.nickName;
    }
    return {
      title: nickname + '超值推荐' + that.data.goods_name,
      path: '/pages/goods-details/goods-details?item=' + JSON.stringify(that.data.item),
      imageUrl: that.data.imgUrls[0],

    }
  },

})